<?php

$drivers = Array();
$drivercount = 0;
$state = '';

if (!($fp=@fopen("./file.xml", "r"))) 
	die ("Couldn't open XML.");

function startElementHandler ($parser,$name,$attrib)
{
global $state;
//echo $name;
$state=$name;
}


function characterDataHandler ($parser, $data) 
{
	global $drivercount;
	global $drivers;
	global $state;
	
	if (!$state) 
	{
		return;
	}
	if ($state=="NAME") { 
		$drivers[$drivercount]["Name"] = $data;
		$drivers[$drivercount]["Laps"] = Array();
	}
	if ($state=="LAP") 
	{ 
		$drivers[$drivercount]["Laps"][] = $data;
	}
}

function endElementHandler ($parser,$name)
{
	global $drivercount;
	global $state;
//echo $name;
	$state='';
	if($name=="DRIVER") {$drivercount++;}
}


if (! ($xml_parser = xml_parser_create()) )
{ 
   die ("Cannot create parser");
}
xml_set_element_handler( $xml_parser, "startElementHandler", "endElementHandler");
xml_set_character_data_handler( $xml_parser, "characterDataHandler");

while( $data = fread($fp, 4096))
{
	if(!xml_parse($xml_parser, $data, feof($fp)))
	{
		echo $data . ' ' . sprintf('XML error %d:"%s" at line %d column %d byte %d', 
				xml_get_error_code($xml_parser), 
				xml_error_string($xml_parser), 
				xml_get_current_line_number($xml_parser), 
				xml_get_current_column_number($xml_parser), 
				xml_get_current_byte_index($xml_parser));
		break;
	}
}
			
xml_parser_free($xml_parser);

function compare_drivers($a, $b)
{
	return $a['best3'] > $b['best3'];
}

foreach($drivers as $key=>$driver)
{
	$lc = 0;
	$lc_tot = 0;
	$lc_last_tot = 999999999999999;
	for($x = 0; $x < sizeof($driver["Laps"]); $x++)
	{
		if(is_numeric($driver["Laps"][$x]))
		{
			$lc++;
			$lc_tot += $driver["Laps"][$x];
		}
		else
		{
			$lc = 0;
			$lc_tot = 0;
		}
		
		if($lc == 3)
		{
			if($lc_tot < $lc_last_tot)
			{
				$lc_last_tot = $lc_tot;
			}
			
			$lc--;
			$lc_tot -= $driver["Laps"][$x - 2];
		}
	}
	$drivers[$key]['best3'] = $lc_last_tot;
}

usort($drivers, "compare_drivers");

foreach($drivers as $driver)
{
	echo $driver["Name"] . ', ' ;
	foreach($driver["Laps"] as $lap)
	{
		echo $lap . ', ';
	}
	if($driver["best3"] != 999999999999999)
		echo $driver["best3"];
	echo "<br>";
}
?>